import React, { useState, memo, useEffect, useCallback } from 'react';
import { Table, Row, Col, Button, message, Select } from 'tdesign-react';
import { userList,editUserInfoApi } from 'api/user';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { CHANNEL_PROMOTION_MAP, PLATFORM_OPTIONS, PROMOTION_MAP, USER_TYPE_MAP, USER_TYPE_OPTIONS } from 'constants/index';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import IppeakTable from 'components/IppeakTable';
import { createRequestParams, filterEmptyValues } from 'utils';
import SakuraDrawer from 'components/SakuraDrawer';
import { SOURCE_OPTIONS, USER_STATUS_OPTIONS } from './consts';

// 初始查询参数
const INITIAL_QUERY = {
  page: 1,
  page_size: 10,
  username: '',
  tags: '',
};

// 初始表格状态
const INITIAL_TABLE_STATE = {
  list: [],
  total: 0,
  current: 1,
  pageSize: 10,
};

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const { loading, setLoading } = useLoading(false);
  const [hideQuerys, sethideQuerys] = useState<{ qudao: boolean; tuiguang: boolean }>({
    qudao: true,
    tuiguang: true,
  });

  // 表格状态管理
  const [table, setTable] = useState(INITIAL_TABLE_STATE);
  const [query, setQuery] = useState<any>(INITIAL_QUERY);

  // 统一的字段清除处理函数
  const handleFieldClear = (fieldName: string) => {
    setQuery((prev: any) => {
      const { [fieldName]: removed, ...rest } = prev || {};
      return { ...rest, };
    });
  };

  const clearFieldAtDate = (value: string) => {
    if(!value.length){
      delete query.start_time
      delete query.end_time
      setQuery((pre: any) => ({
        ...pre,
        page:1,
        page_size:pre.page_size || 10
      }))
    }
  }
  // Drawer 相关状态
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);

  const { list, total } = table;

  // 表格列定义
  const columns = createColumns([
    {
      label: '用户ID',
      key: 'id',
      width: '70',
    },
    {
      label: '邮箱',
      key: 'email',
      width: 180,
    },
    {
      label: '用户类型',
      key: 'tags',
      render({ row }: any) {
        const tagColor = row.tags === 'vip' ? '#7868e6' : row.tags === 'staff' ? '#f80' : 'inherit';
        return <span style={{ color: tagColor, cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>;
      },
    },
    {
      label: '用户状态',
      key: 'user_status',
    },
    {
      label: '来源',
      key: 'source',
      width: '180',
    },
    {
      label: '注册时间',
      key: 'created',
      type: 'date',
      width: '140',
    },
    {
      label: '注册IP',
      width: '120',
      key: 'ip',
    },
    {
      label: '注册地(时区)',
      key: 'region',
      width: '180',
    },
    {
      label: '激活时间',
      key: 'active_time',
      type: 'date',
      width: '140',
    },
    {
      label: '操作',
      key: 'operation',
      align: 'center',
      fixed: 'right',
      width: '100',
      render: ({ row }: any) => {
        return <Button theme='primary' variant='text' onClick={() => clickEdit(row)}>编辑</Button>;
      },
    }
  ]);

  // 表单字段定义
  const formFields: any[] = [
    {
      label: '用户ID',
      name: 'uid',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 65,
        width: 86,
      },
    },
    {
      label: '邮箱',
      name: 'username',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 50,
        width: 156,

      },
    },
    {
      label: '用户类型',
      name: 'tags',
      type: 'select',
      options: USER_TYPE_OPTIONS,
    },
    {
      label: '用户状态',
      name: 'status',
      type: 'select',
      options: USER_STATUS_OPTIONS
    },
    {
      label: '来源',
      type: 'select',
      name:'a_source',
      options: SOURCE_OPTIONS,
      colWrap: {
        colSpan: 1.5,
        labelWidth: 50,
      },
      onChange: (value: any) => { handleSource(value) }
    },
    {
      label: '渠道名称',
      name: 'channel_name',
      type: 'input',
      hide: hideQuerys.qudao,
    },
    {
      label: '推广系列',
      name: 'series',
      type: 'input',
      hide: hideQuerys.tuiguang,
    },
    {
      label: '注册时间',
      name: 'register_time',
      type: 'date',
      returnType:'timestamp',
      onChange: clearFieldAtDate,
     
    },
  ];

  // 获取用户列表数据
  const fetchUserList = useCallback(
    async (params?: any) => {
      setLoading(true);
      delete (query as any)?.register_time
      try {
        // 合并参数并过滤空值，使用当前查询参数中的页码
        const requestParams = createRequestParams({ ...query });
        const res: any = await userList(requestParams);
        setLoading(false);
        setTable((pre: any) => ({
          ...pre,
          list: res.results || [],
          total: res.total || 0,
        }));
      } catch (err) {
        setLoading(false);
      }
    },
    [query],
  );

  const clickEdit = useCallback((row: any) => {
    console.log(row,'row')
    setEditingUser({...row,user_status:row.user_status=='未激活'?'':USER_STATUS_OPTIONS.find(item=>item.label==row.user_status)?.value});
    setDrawerVisible(true);
  }, []);

  // 处理选择变化
  const onSelectChange = useCallback((value: (string | number)[]) => {
    setSelectedRowKeys(value);
  }, []);
  useEffect(()=>{
    if(!query.a_source){
      delete query?.origin
      delete query?.channel
      delete query?.source
      delete query?.channel_name
      delete query?.series
    }
  }, [query.a_source]);
  // 处理搜索
  const handleSearch = useCallback((values: any) => {
    let platforms = PLATFORM_OPTIONS.map(item=>(item.label))
    let promotions = PROMOTION_MAP.map(item=>(item.label)) // 推广
    let biddings =  CHANNEL_PROMOTION_MAP.map(item=>(item.label)) // 渠道
    let type = ''
    if(values.a_source == 1||values.a_source==2){
      type='origin'
    }else if(promotions.includes(values.a_source)){
        type='source'
        delete values.channel_name
    }else if(biddings.includes(values.a_source)){
      type='channel'
      delete values.series
    }
    const startTime = values?.register_time?.[0] || '';
    const endTime = values?.register_time?.[1] || '';
    const query = {
      ...values,
      [type]:values.a_source,
      start_time: startTime,
      end_time: endTime,
    }
    setQuery((pre: any)=>({
        ...query,
        page:1,
        page_size:pre.page_size || 10
    }))
  }, []);

  // 处理重置
  const handleReset = () => {
    setQuery((pre: any)=>({
      page:1,
      page_size:10
    }));
  }

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize: number) => {
    setQuery((pre: any) => ({
      ...pre,
      page,
      page_size: pageSize,
    }));
  }

  // 处理当前页变化
  const handleCurrentChange = 
    (current: number, pageInfo: any) => {
      handlePaginationChange(pageInfo.current, query.page_size);
    }
    
  const handleSource =(value: string)=>{
    let platforms = PLATFORM_OPTIONS.map(item=>(item.label))
    let promotions = PROMOTION_MAP.map(item=>(item.label)) // 推广
    let biddings =  CHANNEL_PROMOTION_MAP.map(item=>(item.label)) // 渠道
    if(promotions.includes(value)){
      sethideQuerys((pre: { qudao: boolean; tuiguang: boolean }) => ({...pre,tuiguang:false,qudao:true}))
    }else if(biddings.includes(value)){
      sethideQuerys((pre: { qudao: boolean; tuiguang: boolean }) => ({...pre,qudao:false,tuiguang:true}))
    }else{
      sethideQuerys((pre: { qudao: boolean; tuiguang: boolean }) => ({
        ...pre,
        qudao: true,
        tuiguang: true,
      }))
    }

  }

  // 处理每页条数变化
  const handlePageSizeChange = useCallback(
    (size: number) => {
      handlePaginationChange(1, size); // 切换每页条数时重置到第一页
    },
    [handlePaginationChange],
  );
  const handleClose = useCallback(() => {
    setVisible(false);
  }, []);

  // Drawer 相关处理函数
  const handleDrawerClose = useCallback(() => {
    setDrawerVisible(false);
    setEditingUser(null);
  }, []);

  const handleDrawerSubmit = useCallback(async (type: string, values: any, cb: () => void) => {
    try {
      const userId = editingUser?.id;
      const requestData = {
        status:values.user_status,
        type:values.tags,
        id: userId
      };
      await editUserInfoApi(filterEmptyValues(requestData));
      setDrawerVisible(false)
      cb();
      fetchUserList();
      message.success('更新用户信息成功');
    } catch (error) {
      console.error('更新用户信息失败:', error);
    }
  }, [editingUser, fetchUserList]);

  // Drawer 表单字段配置
  const drawerFormFields = [
   
    {
      label: '邮箱',
      name: 'email',
      type: 'input' as const,
      disabled: true,
    },
    {
      label: '用户类型',
      name: 'tags',
      type: 'select' as const,
      options: USER_TYPE_OPTIONS,
    },
    {
      label: '用户状态',
      name: 'user_status',
      type: 'render' as const,
      render: (form: any, field: any) => {
        const options = [{label:'正常',value:1},{label:'禁用',value:2}];
        const currentValue = form?.getFieldValue?.(field.name);
        const hasValidOption = options.some(option => option.value === currentValue);
        
        return <Select
          value={hasValidOption ? currentValue : undefined}
          options={options}
          onChange={(value) => {
            form.setFieldsValue({ [field.name]: value });
          }}
        />
      },
    },
  ];
  // 监听查询参数变化，自动获取数据
  useEffect(() => {
    fetchUserList();
  }, [fetchUserList]);

  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm 
            fields={formFields} 
            onSearch={handleSearch} 
            onReset={handleReset}
            onFieldClear={handleFieldClear}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        tableHeight={320}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: query.page_size,
          total,
          current: query.page,
          showJumper: true,
          onCurrentChange: handleCurrentChange,
          onPageSizeChange: handlePageSizeChange,
        }}
      />
      
      {/* 用户编辑 Drawer */}
      <SakuraDrawer
        visible={drawerVisible}
        onClose={handleDrawerClose}
        onConfirm={handleDrawerSubmit}
        title="用户"
        type="Edit"
        drawerFormFields={drawerFormFields}
        initialValues={editingUser}
        width="600px"
      />
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
